package android.slc.appbase.ui.dialog;

import android.slc.box.commonlibrary.compat.SlcResourceUtils;
import android.slc.box.core.scope.IntentScope;
import de.saxsys.mvvmfx.FluentViewLoader;
import de.saxsys.mvvmfx.FxmlView;
import de.saxsys.mvvmfx.InjectViewModel;
import de.saxsys.mvvmfx.ViewTuple;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.stage.WindowEvent;
import org.apache.commons.lang3.StringUtils;
import org.controlsfx.tools.Utils;

public class LoadingDialogView implements FxmlView<LoadingDialogVm> {

    public static final String KEY_MSG = "message";

    public static Stage show(String message) {
        return show(message, false);
    }

    public static Stage show(String message, boolean cancelable) {
        return show(message, cancelable, null);
    }

    public static Stage show(String message, boolean cancelable, EventHandler<WindowEvent> onHidden) {
        return show(Utils.getWindow(null), message, cancelable, onHidden);
    }

    public static Stage show(Window window, String message) {
        return show(window, message, false);
    }

    public static Stage show(Window window, String message, boolean cancelable) {
        return show(window, message, cancelable, null);
    }

    public static Stage show(Window window, String message, boolean cancelable, EventHandler<WindowEvent> onHidden) {
        Stage stage = new Stage();
        SlcPopup.initModality(stage, window);
        SlcPopup.initStyle(stage, cancelable);
        IntentScope intentScope = new IntentScope();
        intentScope.setBundle(SlcPopup.createBundle(StringUtils.isEmpty(message) ? SlcResourceUtils.getString("label_is_loading") : message));
        ViewTuple<LoadingDialogView, LoadingDialogVm> viewTuple = FluentViewLoader.fxmlView(LoadingDialogView.class).providedScopes(intentScope).load();
        Scene scene = new Scene(viewTuple.getView());
        SlcPopup.applyStylesheets(scene);
        stage.setScene(scene);
        if (onHidden != null) {
            stage.setOnHidden(onHidden);
        }
        stage.show();
        return stage;
    }

    @InjectViewModel
    private LoadingDialogVm loadingDialogVm;

    @FXML
    private ProgressIndicator progressIndicator;

    @FXML
    private Label message;


    /**
     * 此方法由mvvmFx框架调用
     * 初始化
     */
    public final void initialize() {
        message.setText(SlcPopup.getMsg(loadingDialogVm.getIntentScope().getBundle()));
    }

}
